package org.cx.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



import com.cx.service.RedisService;

import com.cx.utils.RedisKeyUtil;
import org.cx.entity.Page;
import org.cx.entity.PageData;
import org.cx.util.FastJsonUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 抽象控制器，可继承顶级公共控制器
 * 
 * @author Hungel.zou
 * @since 2013-8-30 上午11:10:02
 * @version 1.0
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public abstract class BaseController {

	protected static String SUCCESS = "0";
	protected static String DATA_ERROR = "-1";
	protected static String EXCEPTION = "-2";

	protected static String SUCC = "操作成功";
	protected static String FAIL = "操作失败";

	protected static final String CONTENT_TYPE_ZIP = "application/zip;charset=UTF-8";

	@Resource
	private RedisService redisService;

	/**
	 * 返回成功数据
	 * 
	 * @param T
	 * @return
	 */
	protected ApiModel buildSuccMsg(Object T) {
		ApiModel ret = new ApiModel();
		ret.setStatus(SUCCESS);
		ret.setErrorMsg(SUCC);
		ret.setBody(T);
		return ret;
	}

	/**
	 * 返回失败数据
	 * 
	 * @param T
	 * @param errorCode
	 * @param msg
	 * @return
	 */
	protected ApiModel buildErrorMsg(Object T, String errorCode, String msg) {
		ApiModel ret = new ApiModel();
		ret.setStatus(errorCode);
		ret.setErrorMsg(msg != null ? msg : "");
		ret.setBody(T);
		return ret;
	}

	/**
	 * 
	 * @param msg
	 * @return
	 */
	protected ApiModel buildErrorMsg(String msg) {
		if (msg != null) {
			return buildErrorMsg(msg, DATA_ERROR, msg);
		} else {
			return buildSuccMsg(SUCC);
		}
	}

	/**
	 * 获取Session
	 * 
	 * @return
	 * @throws Exception
	 */
	protected HttpSession getSession() throws Exception {
		return ((ServletRequestAttributes) RequestContextHolder
				.currentRequestAttributes()).getRequest().getSession();
	}

	protected void invalidate() throws Exception {
		HttpSession session = getSession();
		session.invalidate();
	}

	/**
	 * 获得响应的完整URL地址
	 * 
	 * @param request
	 * @return
	 */
	protected String getRequestURL(HttpServletRequest request) {
		String queryStr = request.getQueryString();
		String url = "http://"
				+ request.getServerName() // 服务器地址
				+ ":"
				+ ((request.getServerPort() == 80) ? "" : request
						.getServerPort()) // 端口号
				+ request.getContextPath() // 项目名称
				+ request.getServletPath() // 请求页面或其他地址
				+ (queryStr != null ? "?" + queryStr : ""); // 参数
		return url;
	}

	protected void out(HttpServletResponse response, String path,
			String contentType) throws Exception {
		InputStream is = null;
		ServletOutputStream out = null;
		try {
			// response.setContentType("application/zip;charset=UTF-8");

			response.setContentType(contentType);
			response.setHeader("Cache-Control", "no-cache");

			String fileName = path.substring(
					path.lastIndexOf(File.separator) + 1, path.length());
			response.addHeader("Content-Disposition", "attachment;filename=\""
					+ fileName + "\"");
			out = response.getOutputStream();

			byte[] buffer = new byte[1024];
			int len = 0;
			is = new FileInputStream(new File(path));
			while ((len = is.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
			out.flush();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (is != null) {
				is.close();
			}
			if (out != null) {
				out.close();
			}
		}
	}
	
	public Page getPage() {
		return new Page(getRequest());
	}
	
	public PageData getPageData() {
		return new PageData(getRequest());
	}
	
    public HttpServletRequest getRequest(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return request;
    }

	public Map<String,Object> getUserInfo(PageData pd) {
		String userInfo = (String) redisService.get(pd.getString("token"));
		return FastJsonUtils.json2map(userInfo);
	}

	public void setUserInfo(PageData pd) {
		Map<String, Object> user = getUserInfo(pd);
		pd.put("actId", user.get("actid"));
		pd.put("userId", user.get("clerkid"));
		pd.put("userName", user.get("clerkname"));
		pd.put("userPhone", user.get("clerkphone"));
		pd.put("headImg", user.get("clerkheadurl"));
	}

	public PageData  getUserByToken(){
		String token  = getRequest().getHeader("token");
		return (PageData)redisService.getSession(RedisKeyUtil.getLoginUserKey(token));
	}
    public PageData  getUserByToken(String token){
        return (PageData)redisService.getSession(RedisKeyUtil.getLoginUserKey(token));
    }


}
